package com.weiyi.mashangzhu.Roomer.Activity;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.Request;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.Application.MyApp;
import com.weiyi.mashangzhu.Base.BaseActivity;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Utils.LoadingDialog;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.Utils.T;
import com.weiyi.mashangzhu.wxapi.simcpux.BmpToByteArray;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShareActivity extends BaseActivity {
    TextView pop_friend_wx, pop_friend_wxc, pop_off;
    @BindView(R.id.invite_code)
    TextView inviteCode;
    LinearLayout relativeLayout;
    @BindView(R.id.scrollview_share)
    ScrollView scrollviewShare;
    private Handler mHandler = new Handler();
    private IWXAPI msgApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share);
        ButterKnife.bind(this);
        relativeLayout = (LinearLayout) findViewById(R.id.photo_share);
        initView();
    }

    @Override
    public void initView() {
        super.initView();
        LoadingDialog.show(ShareActivity.this);
        OkHttpUtils.get()
                .addParams("token", SPUtils.get(ShareActivity.this, "token", "") + "")
                .url(API.BaseApi_R + API.GetInviteCode)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        LoadingDialog.dismiss(ShareActivity.this);
                        T.showShort(ShareActivity.this, "数据获取失败，请稍后再试");

                    }

                    @Override
                    public void onResponse(String response) {
                        LoadingDialog.dismiss(ShareActivity.this);
                        if (response != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                if (jsonObject.getInt("status") == 0) {
                                    inviteCode.setText("邀请码：" + jsonObject.getString("data"));
                                } else {
                                    T.showShort(ShareActivity.this, jsonObject.getString("msg"));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                });
    }

    public void showPopupWindow() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_win_friend, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT, true);
        pop_friend_wx = (TextView) contentView.findViewById(R.id.pop_friend_wx);
        pop_friend_wxc = (TextView) contentView.findViewById(R.id.pop_friend_wxc);
        pop_off = (TextView) contentView.findViewById(R.id.pop_off);
        pop_off.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        pop_friend_wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                msgApi = WXAPIFactory.createWXAPI(ShareActivity.this, null);
                msgApi.registerApp("wx29a520b1867fe3a2");
                if (!MyApp.mWxApi.isWXAppInstalled()) {
                    T.showShort(ShareActivity.this, "您还未安装微信客户端");
                    return;
                }
                Bitmap bitmap = getBitmapByView(scrollviewShare);
                if (bitmap != null) {
                    sharePicByFile(bitmap, System.currentTimeMillis() + "", "好友");
                } else {
                    T.showShort(ShareActivity.this, "图片为空");
                }
            }
        });
        pop_friend_wxc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                msgApi = WXAPIFactory.createWXAPI(ShareActivity.this, null);
                msgApi.registerApp("wx29a520b1867fe3a2");
                if (!MyApp.mWxApi.isWXAppInstalled()) {
                    T.showShort(ShareActivity.this, "您还未安装微信客户端");
                    return;
                }

                Bitmap bitmap = getBitmapByView(scrollviewShare);
                if (bitmap != null) {
                    sharePicByFile(bitmap, System.currentTimeMillis() + "", "朋友圈");
                } else {
                    T.showShort(ShareActivity.this, "图片为空");
                }
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.popup_window_bottom_animation);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x55000000));
        // 设置好参数之后再show
        if (popupWindow.isShowing()) {

        } else {
            popupWindow.showAsDropDown(contentView);
        }
    }

    public static Bitmap getBitmapByView(ScrollView scrollView) {
        int h = 0;
        Bitmap bitmap = null;
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();
        }
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.RGB_565);
        final Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);
        return bitmap;
    }

    /**
     * 把一个view转化成bitmap对象
     */
    public Bitmap getViewBitmap(int layoutId) {
        View view = getLayoutInflater().inflate(layoutId, null);
        int me = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(me, me);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

    public void sharePicByFile(Bitmap bitmap, String tag, String info) {
//        if (!picFile.exists()) {return;}
//        Bitmap pic = BitmapFactory.decodeFile(picFile.toString());

        WXImageObject imageObject = new WXImageObject(bitmap);
        //这个构造方法中自动把传入的bitmap转化为2进制数据,或者你直接传入byte[]也行
        //注意传入的数据不能大于10M,开发文档上写的

        WXMediaMessage msg = new WXMediaMessage();  //这个对象是用来包裹发送信息的对象
        msg.mediaObject = imageObject;
        //msg.mediaObject实际上是个IMediaObject对象,
        //它有很多实现类,每一种实现类对应一种发送的信息,
        //比如WXTextObject对应发送的信息是文字,想要发送文字直接传入WXTextObject对象就行


        Bitmap thumbBitmap = Bitmap.createScaledBitmap(bitmap, 150, 150, true);

        msg.thumbData = BmpToByteArray.bmpToByteArray(thumbBitmap);
        //在这设置缩略图
        //官方文档介绍这个bitmap不能超过32kb
        //如果一个像素是8bit的话换算成正方形的bitmap则边长不超过181像素,边长设置成150是比较保险的
        //或者使用msg.setThumbImage(thumbBitmap);省去自己转换二进制数据的过程
        //如果超过32kb则抛异常

        SendMessageToWX.Req req = new SendMessageToWX.Req();    //创建一个请求对象
        req.message = msg;  //把msg放入请求对象中
        if (info.equals("朋友圈")) {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;    //设置发送到朋友圈
        } else {
            req.scene = SendMessageToWX.Req.WXSceneSession;   //设置发送给朋友
        }
        req.transaction = tag;  //这个tag要唯一,用于在回调中分辨是哪个分享请求
        boolean b = msgApi.sendReq(req);   //如果调用成功微信,会返回true
        Log.e("==============", "==" + b);
    }

    /**
     * 保存方法
     */
    public static boolean saveBitmap(String picName, Bitmap bm) {
        File f = new File(Environment.getExternalStorageDirectory(), picName);
        if (f.exists()) {
            f.delete();
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return true;
    }

    public void savePicture(String fileName, Bitmap bm) {
        Log.i("xing", "savePicture: ------------------------");
        if (null == bm) {
            Log.i("xing", "savePicture: ------------------图片为空------");
            return;
        }
//        .getAbsolutePath()
        File foder = new File(Environment.getExternalStorageDirectory(), fileName);
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(foder, fileName);
        try {
            if (!myCaptureFile.exists()) {
                myCaptureFile.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            //压缩保存到本地
            bm.compress(Bitmap.CompressFormat.JPEG, 90, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Toast.makeText(this, "保存成功!", Toast.LENGTH_SHORT).show();

    }

    @OnClick({R.id.back, R.id.share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.share:
                showPopupWindow();
                break;
        }
    }

}
